import {
  Button,
  Card,
  DatePicker,
  Descriptions,
  Drawer,
  Form,
  Input,
  message,
  Select,
  Table,
  Tabs,
  Tag,
  Spin,
} from "antd";
import React, { FC, useEffect, useState } from "react";
import { SearchOutlined, SyncOutlined } from "@ant-design/icons";
import "@/containers/DepartmentManage/views/style.css";
import "./style.css";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { useRequest } from "@umijs/hooks";
import moment from "moment";
import { useForm } from "antd/es/form/Form";
import { uniqueId } from "lodash";
import { ExclamationCircleFilled, CheckCircleFilled } from "@ant-design/icons";
const { TabPane } = Tabs;
//查询框
const Searchs: FC<{ finish: (values: any) => void }> = ({ finish }) => {
  const [form] = Form.useForm();
  const [treeNode, setTreeNode] = useState<any>([]);
  //组装参数
  const params = {
    level: 0,
    treeId: "0",
  };
  const loadData = (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    //组装参数
    const params = {
      level: 0,
      treeId: "0",
    };
    selectedOptions.forEach((item: any) => {
      params.treeId = item.treeId;
      params.level = selectedOptions.length;
    });
    // console.log(params)

    fetchRequest(url.GET_SCHOOL_ORGANIZATION, params)
      .then((json) => {
        if (json.success) {
          console.log(json.data);
          json.data.forEach((item: any) => {
            delete item.children;
          });
          targetOption.children = json.data;
          // console.log(targetOption)
        } else {
          message.error(json.errMsg);
        }
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        targetOption.loading = false;
        //主动刷新页面
        setTreeNode([...treeNode]);
      });
  };

  const handleFinish = (values: any) => {
    //todo
    finish({
      ...values,
      deptId: values.deptId ? values.deptId[values.deptId.length - 1] : "",
      attendStatus:
        values.attendStatus === null ? undefined : values.attendStatus,
    });
  };

  const handleReset = () => {
    finish({
      deptId: "",
      attendStatus: "",
    });
  };

  return (
    <Card className="att-active-warp" bordered={false}>
      {" "}
      <Form
        form={form}
        layout="inline"
        initialValues={{ schoolMark: "", stuCode: "", date: "" }}
        onFinish={handleFinish}
        onReset={handleReset}
      >
        <Form.Item className="form-control-item" name="date" label="考勤时间">
          <DatePicker.RangePicker showTime style={{ width: 350 }} />
        </Form.Item>

        {/* <Form.Item className="form-control-item" name="stuCode" label="学号">
            <Input style={{ width: 100 }} placeholder="请输入学号" />
        </Form.Item>

        <Form.Item className="form-control-item" name="attendStatus" label="归寝状态">
            <Select style={{ width: 100 }} defaultValue={'全部'}>
                <Select.Option >全部</Select.Option>
                <Select.Option value="0">已归寝</Select.Option>
                <Select.Option value="-2">未归寝</Select.Option>
            </Select>
        </Form.Item> */}

        <Form.Item className="form-control-item">
          <Button
            key="1"
            type="primary"
            icon={<SearchOutlined />}
            htmlType="submit"
            style={{ marginRight: "8px" }}
          >
            搜索
          </Button>
          <Button key="2" icon={<SyncOutlined />} htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

const Search: FC<{ finish: (values: any) => void }> = ({ finish }) => {
  const [form] = Form.useForm();
  const [treeNode, setTreeNode] = useState<any>([]);
  //组装参数
  const params = {
    level: 0,
    treeId: "0",
  };
  const loadData = (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    //组装参数
    const params = {
      level: 0,
      treeId: "0",
    };
    selectedOptions.forEach((item: any) => {
      params.treeId = item.treeId;
      params.level = selectedOptions.length;
    });
    // console.log(params)

    fetchRequest(url.GET_SCHOOL_ORGANIZATION, params)
      .then((json) => {
        if (json.success) {
          console.log(json.data);
          json.data.forEach((item: any) => {
            delete item.children;
          });
          targetOption.children = json.data;
          // console.log(targetOption)
        } else {
          message.error(json.errMsg);
        }
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        targetOption.loading = false;
        //主动刷新页面
        setTreeNode([...treeNode]);
      });
  };

  const handleFinish = (values: any) => {
    //todo
    finish({
      ...values,
      deptId: values.deptId ? values.deptId[values.deptId.length - 1] : "",
      attendStatus:
        values.attendStatus === null ? undefined : values.attendStatus,
    });
  };

  const handleReset = () => {
    finish({
      deptId: "",
      attendStatus: "",
    });
  };

  useEffect(() => {}, []);

  return (
    <Card className="att-active-warp" bordered={false}>
      {" "}
      <Form
        form={form}
        layout="inline"
        initialValues={{ schoolMark: "", stuCode: "", date: "" }}
        onFinish={handleFinish}
        onReset={handleReset}
      >
        {/* <Form.Item className="form-control-item" name="date" label="考勤时间">
            <DatePicker.RangePicker showTime style={{ width: 350 }} />
        </Form.Item> */}

        <Form.Item className="form-control-item" name="stuCode" label="学号">
          <Input style={{ width: 100 }} placeholder="请输入学号" />
        </Form.Item>

        <Form.Item
          className="form-control-item"
          name="attendStatus"
          label="归寝状态"
        >
          <Select style={{ width: 100 }} defaultValue={"全部"}>
            <Select.Option>全部</Select.Option>
            <Select.Option value="0">已归寝</Select.Option>
            <Select.Option value="-2">未归寝</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item className="form-control-item">
          <Button
            key="1"
            type="primary"
            icon={<SearchOutlined />}
            htmlType="submit"
            style={{ marginRight: "8px" }}
          >
            搜索
          </Button>
          <Button key="2" icon={<SyncOutlined />} htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

//table
const RulesTable: FC<{ values: any }> = ({ values }) => {
  const [visible, setVisible] = useState(false);
  const [el, setEl] = useState<any>({});
  const { run, tableProps } = useRequest(
    (current, params) =>
      fetchRequest(url.BEDTIME_RECORD_PAGE, {
        pageSize: current.pageSize,
        pageNum: current.current,
        ...params,
      }),
    {
      loadingDelay: 200,
      manual: true,
      paginated: true,
      formatResult: (response: any) => {
        const data = JSON.parse(response.data);
        const list = data?.data?.records.map((item: any) => {
          return {
            id: uniqueId("user"),
            ...item,
          };
        });
        console.log(list);

        return {
          list: list,
          total: data?.data.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
      onSuccess: (json: any) => {
        if (json.success) {
        } else {
          message.error(json.errorMsg);
        }
      },
    }
  );

  const onInfo = (el: any) => {
    setEl(el);
    setVisible(true);
  };

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "学号",
      dataIndex: "studentCode",
      key: "studentCode",
    },
    {
      title: "组织机构",
      dataIndex: "orgPath",
      key: "orgPath",
    },
    {
      title: "时间",
      dataIndex: "updateTime",
      key: "updateTime",
      render(updateTime: string) {
        return <>{moment(updateTime).format("YYYY-MM-DD  hh:mm:ss")} </>;
      },
    },
    {
      title: "归寝状态",
      dataIndex: "studentStatus",
      key: "studentStatus",
    },
    {
      title: "操作",
      render(el: any) {
        return (
          <>
            <Tag color="#1153ff" onClick={() => onInfo(el)}>
              查看
            </Tag>
          </>
        );
      },
    },
  ];
  useEffect(() => {
    if (values.refresh) {
      run(
        { pageSize: 10, current: 1 },
        {
          ...values,
          startDate: values.date
            ? moment(values.date[0]).format("YYYY-MM-DD")
            : "",
          endDate: values.date
            ? moment(values.date[1]).format("YYYY-MM-DD")
            : "",
          dormId: "rootdcms000001",
          orgId: "root000000",
          stuCode: values.stuCode,
          name: "",
          attendStatus: values.attendStatus,
        }
      );
    }
  }, [
    values.attendStatus,
    values.stuCode,
    values.deptId,
    values.refresh,
    values.date,
  ]);

  return (
    <div className="site-card-border-less-wrapper">
      <Card title="考勤结果">
        <Table {...(tableProps as any)} columns={columns} rowKey="id" />
        <Drawer
          title="信息详情"
          placement="right"
          visible={visible}
          onClose={() => setVisible(false)}
          width={800}
        >
          <Descriptions bordered>
            <Descriptions.Item label="姓名">{el.name}</Descriptions.Item>
            <Descriptions.Item label="学号" span={2}>
              {el.studentCode}
            </Descriptions.Item>
            <Descriptions.Item label="头像" span={3}>
              <img src={el.picture} width={80} height={80} alt="头像" />
            </Descriptions.Item>
            <Descriptions.Item label="组织机构" span={3}>
              {el.orgPath}
            </Descriptions.Item>
            <Descriptions.Item label="时间" span={2}>
              {moment(el.updateTime).format("YYYY-MM-DD hh:mm:ss")}
            </Descriptions.Item>
            <Descriptions.Item label="归寝状态">
              {el.studentStatus}
            </Descriptions.Item>
          </Descriptions>
        </Drawer>
      </Card>
    </div>
  );
};

//table
const RulesTableInfo: FC<{ values: any }> = ({ values }) => {
  const [visible, setVisible] = useState(false);
  const [el, setEl] = useState<any>({});
  const { run, tableProps } = useRequest(
    (current, params) =>
      fetchRequest(url.BED_TIMRECORD_PAGE, {
        pageSize: current.pageSize,
        pageNum: current.current,
        ...params,
      }),
    {
      loadingDelay: 200,
      manual: true,
      paginated: true,
      formatResult: (response: any) => {
        const data = JSON.parse(response.data);
        const list = data?.data?.records.map((item: any) => {
          return {
            id: uniqueId("user"),
            ...item,
          };
        });
        console.log(list);

        return {
          list: list,
          total: data?.data.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
      onSuccess: (json: any) => {
        if (json.success) {
        } else {
          message.error(json.errorMsg);
        }
      },
    }
  );

  const onInfo = (el: any) => {
    setEl(el);
    setVisible(true);
  };

  const columns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "学号",
      dataIndex: "studentCode",
      key: "studentCode",
    },
    {
      title: "组织机构",
      dataIndex: "orgPath",
      key: "orgPath",
    },
    {
      title: "时间",
      dataIndex: "updateTime",
      key: "updateTime",
      render(updateTime: string) {
        return <>{moment(updateTime).format("YYYY-MM-DD  hh:mm:ss")} </>;
      },
    },
    {
      title: "归寝状态",
      dataIndex: "stuAttendanceStatusName",
      key: "stuAttendanceStatusName",
    },
    {
      title: "操作",
      render(el: any) {
        return (
          <>
            <Tag color="#1153ff" onClick={() => onInfo(el)}>
              查看
            </Tag>
          </>
        );
      },
    },
  ];
  useEffect(() => {
    if (values.refresh) {
      run(
        { pageSize: 10, current: 1 },
        {
          startDate: values.date
            ? moment(values.date[0]).format("YYYY-MM-DD")
            : "",
          endDate: values.date
            ? moment(values.date[1]).format("YYYY-MM-DD")
            : "",
          dormId: "rootdcms000001",
          orgId: "root000000",
          stuCode: values.stuCode,
          name: "",
          attendStatus: values.attendStatus,
        }
      );
    }
  }, [
    values.attendStatus,
    values.stuCode,
    values.deptId,
    values.refresh,
    values.date,
  ]);

  return (
    <div className="site-card-border-less-wrapper">
      <Card title="考勤结果">
        <Table {...(tableProps as any)} columns={columns} rowKey="id" />
        <Drawer
          title="信息详情"
          placement="right"
          visible={visible}
          onClose={() => setVisible(false)}
          width={800}
        >
          <Descriptions bordered>
            <Descriptions.Item label="姓名">{el.name}</Descriptions.Item>
            <Descriptions.Item label="学号" span={2}>
              {el.studentCode}
            </Descriptions.Item>
            <Descriptions.Item label="头像" span={3}>
              <img src={el.picture} width={80} height={80} alt="头像" />
            </Descriptions.Item>
            <Descriptions.Item label="组织机构" span={3}>
              {el.orgPath}
            </Descriptions.Item>
            <Descriptions.Item label="时间" span={2}>
              {moment(el.updateTime).format("YYYY-MM-DD hh:mm:ss")}
            </Descriptions.Item>
            <Descriptions.Item label="归寝状态">
              {el.stuAttendanceStatusName}
            </Descriptions.Item>
          </Descriptions>
        </Drawer>
      </Card>
    </div>
  );
};

//tabl
const Result: FC = () => {
  const [form] = useForm();
  const [state, setState] = useState(false);
  const { data, run, loading } = useRequest(
    (params) => fetchRequest(url.ATTENDANCERESULTS, params),
    {
      manual: true,
      formatResult: (res: any) => {
        setState(true);
        return {
          ...res,
          data: JSON.parse(res.data),
        };
      },
      onSuccess: (json: any) => {
        const data = json.data;
        if (json.success) {
          console.log(data.data);
        } else {
          message.error(json.errorMsg);
        }
      },
    }
  );

  const change = (value: any) => {
    console.log(value);

    // run({
    //     date: value.format('YYYY-MM-DD'),
    //     "dormName": "",
    //     "ruleName": "测试"
    // })
  };
  const [treeNode, setTreeNode] = useState<any>([]);
  const params = {
    level: 0,
    treeId: "0",
  };
  const loadData = (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    //组装参数
    const params = {
      level: 0,
      treeId: "0",
    };
    selectedOptions.forEach((item: any) => {
      params.treeId = item.treeId;
      params.level = selectedOptions.length;
    });
    // console.log(params)

    fetchRequest(url.GET_SCHOOL_ORGANIZATION, params)
      .then((json) => {
        if (json.success) {
          console.log(json.data);
          json.data.forEach((item: any) => {
            delete item.children;
          });
          targetOption.children = json.data;
          // console.log(targetOption)
        } else {
          message.error(json.errMsg);
        }
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        targetOption.loading = false;
        //主动刷新页面
        setTreeNode([...treeNode]);
      });
  };

  //请求在校学生组织机构

  useEffect(() => {}, []);

  const onFinish = (value: any) => {
    run({
      date: moment(value.date).format("YYYY-MM-DD"),
      dormName: "",
      ruleName: "测试",
      deptId: value.deptId ? value.deptId[value.deptId.length - 1] : "",
    });
  };

  return (
    <>
      <Card bordered={false} className="att-active-warp">
        <Form
          layout="inline"
          onFinish={onFinish}
          form={form}
          initialValues={{
            date: moment(),
          }}
        >
          <Form.Item className="form-control-item" name="date" label="考勤时间">
            <DatePicker onChange={change} allowClear={false} />
          </Form.Item>
          <Form.Item className="form-control-item">
            <Button
              key="1"
              type="primary"
              icon={<SearchOutlined />}
              htmlType="submit"
              style={{ marginRight: "8px" }}
            >
              搜索
            </Button>
            <Button
              key="2"
              icon={<SyncOutlined />}
              htmlType="reset"
              onClick={() => setState(false)}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card className="search-form att-wrap" bordered={false}>
        <Spin spinning={loading}>
          <div className="att-title">考勤结果</div>
          <div className="att-item-wrap">
            <CheckCircleFilled
              style={{ color: "#7cb305", fontSize: "20px" }}
              className="att-icon"
            />
            正常人数： {state ? data?.data?.data?.normalCount : ""}
          </div>
          <div className="att-item-wrap">
            <ExclamationCircleFilled
              style={{ color: " #f5222d", fontSize: "20px" }}
              className="att-icon"
            />{" "}
            异常人数： {state ? data?.data?.data?.noComeCount : ""}
          </div>
        </Spin>
      </Card>
    </>
  );
};

const VideoAttendance: FC = () => {
  const [value, setValues] = useState({
    refresh: false,
  });

  const [values, setValuess] = useState({
    refresh: false,
  });

  const finish = (values: any) => {
    setValues({
      ...values,
      refresh: true,
    });
  };
  const finishs = (values: any) => {
    setValuess({
      ...values,
      refresh: true,
    });
  };
  return (
    <>
      <Tabs defaultActiveKey="1" className="tabs-wrap">
        <TabPane tab="考勤总览" key="1">
          <Result />
        </TabPane>
        <TabPane tab="今日考勤" key="2">
          <Search finish={finish} />
          <RulesTable values={value} />
        </TabPane>
        <TabPane tab="考勤结果" key="3">
          <Searchs finish={finishs} />
          <RulesTableInfo values={values} />
        </TabPane>
      </Tabs>
    </>
  );
};

export default VideoAttendance;
